<template>
  <el-container>
    <el-header height="60">
      <el-button type="primary" @click="showAddDialog">添加学生</el-button>
    </el-header>

    <el-main>
      <el-card>
        <div slot="header">
          <span>班级：{{ classInfo.className }}</span>
        </div>
        <el-table v-loading="loading" :data="studentList" border>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="studentName" label="学生姓名"></el-table-column>
          <el-table-column prop="joinTime" label="加入时间"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="handleRemove(scope.row)">移除</el-button>
              <el-button type="warning" size="mini" @click="showUpdateNoticeDialog(scope.row)">可视化分析</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNo"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
    </el-main>
    //分析
    <el-dialog title="学习者能力分析" :visible.sync="dialogVisible2" width="800px" @close="resetAddForm"
               center>
      <el-container>
        <el-row>
          <div id="leidatu" style="width: 800px;height:400px;"></div>
        </el-row>

      </el-container>

      <div slot="footer" class="dialog-footer">
      </div>
    </el-dialog>

    <!-- 添加学生对话框 -->
    <el-dialog title="添加学生" :visible.sync="dialogVisible" width="500px">
      <el-form :model="studentForm" :rules="rules" ref="studentForm" label-width="100px">
        <el-form-item label="选择学生" prop="studentId">
          <el-select v-model="studentForm.studentId" filterable placeholder="请选择学生">
            <el-option
              v-for="item in availableStudents"
              :key="item.id"
              :label="item.trueName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import classApi from '@/api/class'
import user from '@/api/user'
import statistic from "@/api/statistic";

export default {
  name: 'ClassStudentManage',
  data() {
    return {
      loading: false,
      classId: null,
      classInfo: {},
      studentList: [],
      dialogVisible: false,
      dialogVisible2:false,
      availableStudents: [], // 可选的学生列表
      // 查询参数
      queryInfo: {
        pageNo: 1,
        pageSize: 10,
        classId: null
      },
      total: 0, // 总记录数
      studentForm: {
        classId: null,
        studentId: null,
        status: 1
      },
      rules: {
        studentId: [
          { required: true, message: '请选择学生', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 获取班级信息
    classApi.getMyClass().then(resp => {
      if (resp.code === 200) {
        this.classInfo = resp.data
        this.classId = resp.data.id
        this.queryInfo.classId = this.classId
        this.getStudentList()
        this.getAvailableStudents()
      }
      else {
        this.$message.error('获取班级信息失败,可能没有分配班级')
      }
    })
  },
  methods: {
    //表单信息重置
    resetAddForm () {
      //清空表格数据
      this.$refs['addForm'].resetFields()
    },
    // 添加雷达图绘制方法
    drawRadar() {
      let myChart = this.$echarts.init(document.getElementById('leidatu'));

      // 计算百分比后的值
      let valuesInPercent = this.radarData.values.map(v => ((v / this.radarData.zf) * 100).toFixed(1));

      myChart.setOption({
        title: {
          text: '能力分析雷达图',
          x: 'center',
        },
        radar: {
          indicator: this.radarData.categories.map(category => ({
            name: category, // 确保每个属性名称正确显示
            max: 100, // 100% 为满值
            color: '#409EFF'
          })),
          shape: 'circle',
          splitNumber: 5, // 让刻度更均匀
          radius: '70%',
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            let tooltipContent = `<strong>${params.seriesName}</strong><br/>`;
            params.value.forEach((val, i) => {
              tooltipContent += `${this.radarData.categories[i]}: ${val}%<br/>`;
            });
            return tooltipContent;
          }
        },
        series: [{
          name: '能力得分',
          type: 'radar',
          data: [{
            value: valuesInPercent,
            name: '能力得分', // 这里确保 `name` 仍然正确
            areaStyle: {
              color: 'rgba(64,158,255,0.3)'
            },
            lineStyle: {
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            }
          }]
        }]
      });
    },
    showUpdateNoticeDialog(row){
      this.dialogVisible2 = true;
      this.pieData = [];
      var that =this;
      // 添加雷达图
      statistic.huaxiang({ 'userId': row.studentId }).then((resp) => {
        var list = resp.data;
        var df = 0;
        var categories = list.map(item => item.name);
        var values = list.map(item => item.value);
        var total = values.reduce((sum, val) => sum + val, 0);
        list.forEach(item => {
          df+=item.value;
        });
        this.radarData = {
          categories: categories,
          values: values,
          zf: total ||100
        }
        that.drawRadar();
      })
    },
    // 获取学生列表
    async getStudentList() {
      this.loading = true
      try {
        const resp = await classApi.getClassStudentList(this.queryInfo)
        if (resp.code === 200) {
          this.studentList = resp.data.data
          this.total = resp.data.total
        }
      } catch (error) {
        console.error('获取学生列表失败:', error)
      }
      this.loading = false
    },
    // 监听每页显示数量变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getStudentList()
    },
    // 监听页码变化
    handleCurrentChange(newPage) {
      this.queryInfo.pageNo = newPage
      this.getStudentList()
    },
    // 获取可选的学生列表
    async getAvailableStudents() {
      try {
        const resp = await user.getUserInfo2({
          pageNo: 1,
          roleId: 1, // 学生角色ID
          pageSize: 999
        })
        if (resp.code === 200) {
          this.availableStudents = resp.data.data
        }
      } catch (error) {
        console.error('获取可选学生列表失败:', error)
      }
    },
    // 显示添加对话框
    showAddDialog() {
      this.studentForm = {
        classId: this.classId,
        studentId: null,
        status: 1
      }
      this.dialogVisible = true
    },
    // 提交表单
    handleSubmit() {
      this.$refs.studentForm.validate(async (valid) => {
        if (valid) {
          try {
            const resp = await classApi.addStudentToClass(this.studentForm)
            if (resp.code === 200) {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getStudentList()
            }
          } catch (error) {
            console.error('添加学生失败:', error)
          }
        }
      })
    },
    // 移除学生
    handleRemove(row) {
      this.$confirm('确认移除该学生吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const resp = await classApi.removeStudentFromClass({
            classId: this.classId,
            studentId: row.studentId
          })
          if (resp.code === 200) {
            this.$message.success('移除成功')
            this.getStudentList()
          }
        } catch (error) {
          console.error('移除学生失败:', error)
        }
      }).catch(() => {})
    },
    // 返回上一页
    goBack() {
      this.$router.push('/classManage')
    }
  }
}
</script>

<style scoped>
.el-container {
  height: 100%;
}
.el-header {
  padding: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
